<!--  -->
<template>
    <div class="validate-input-container pb-3">
        <!-- :class="[inputRef.error ? 'is-invalid': (isValid ? 'is-valid': '')]" -->
        <input class="form-control" :class="{'is-invalid': inputRef.error}" 
               v-model="inputRef.val" 
               @blur="validateInput" 
               v-bind="$attrs" 
               v-if="tagType =='input'">

        <textarea rows="4" 
                  class="form-control"  
                 :class="{'is-invalid': inputRef.error}" 
                 v-model="inputRef.val" 
                 @blur="validateInput" 
                 v-bind="$attrs" v-else>
        </textarea>
        <!-- <span v-if="inputRef.error" :class="[inputRef.error? 'invalid-feedback': 'valid-feedback']">{{inputRef.message}}</span> -->
        <span v-if="inputRef.error" class="invalid-feedback">{{inputRef.message}}</span>
    </div>
</template>

<script lang='ts'>
const emailReg = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
import { defineComponent, onMounted, PropType, reactive, ref, watch } from 'vue';
import { emitter } from './ValidateForm.vue'

// 校验类型： custom自定义类型
interface RuleProp {
    type: 'required' | 'email' | 'password' | 'custom';
    message: string;
    validator?: () => boolean     // 2021-02-24新增
};
export type RulesProp = RuleProp[];
// 2021-2-4 添加支持textarea
export type TagType = 'input' | 'textarea'
export default defineComponent({
   name: 'check',
   props: {
       // 校验规则
       rules: {
           type: Array as PropType<RulesProp>,
            default: () => []
        },
        
        // 父组件传来的默认值，用于双向绑定
        modelValue: {
            type: String,
            default: ''
        },

        // input type类型
        tagType: {
            type: String as PropType<TagType>,
            default: 'input'
        }
    },

    // 禁用 Attribute 继承
    inheritAttrs: false,
      
   setup(props, context) {

       const inputRef = reactive({
           val:  props.modelValue,
           error: false,
           message: ''
       })

       const isValid = ref(false);

       const validateInput = () => {
            isValid.value = true
           const rules = props.rules;
           if(rules.length > 0) {
               const allPassed = rules.every( rule => {
                   inputRef.message = rule.message;
                   let passed = true;
                   switch(rule.type) {
                       case 'required':
                           passed = (inputRef.val.trim() !== '')
                           break;
                        case 'email': 
                           passed = emailReg.test(inputRef.val)
                           break;
                        case 'custom': 
                             passed = rule.validator ? rule.validator() : true
                            break;   
                        default: 
                           break;      
                   }
                   return passed;
               })
               inputRef.error = !allPassed
            //    if(allPassed) {
            //        context.emit('update:modelValue', inputRef.val)
            //    }
               return allPassed;
           }
       }

       onMounted(() => {
           emitter.emit('form-item-created', validateInput)
       })

       watch(() => inputRef.val, (val, oldVal) => {
           inputRef.val = val
       })

       return {
           isValid,
           inputRef,
           validateInput
       }
   },
})
</script>
<style lang='scss' scoped>
</style>